﻿using zijian666.Data.SqlBuilders;

namespace zijian666.Data;
public static class DbProviderExtensions
{
    private static readonly ConcurrentDictionary<Type, string?> _providerInvariantNameMapping = [];

    /// <summary>
    /// 获取数据库连接的提供程序名称
    /// </summary>
    public static string? GetProviderInvariantName(this IDbConnection connection)
    {
        ArgumentNullException.ThrowIfNull(connection);
        return _providerInvariantNameMapping.GetOrAdd(connection.GetType(), findProviderInvariantName);

        string? findProviderInvariantName(Type type)
        {
            var names = DbProviderFactories.GetProviderInvariantNames();

            foreach (var name in names)
            {
                var factory = DbProviderFactories.GetFactory(name);
                using var conn = factory.CreateConnection();
                if (conn?.GetType() == type)
                {
                    return name;
                }
            }
            return null;
        }
    }
}
